package cn.lzx.transaction.programme;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * Created by lzx on 2016/12/9.
 * 编程式事务
 */
@Service
public class BusinessServiceProgram {

    @Autowired
    private CustomerServiceProgram customerService;

    @Autowired
    private ProducerServiceProgram producerService;

    @Autowired
    private TransactionTemplate transactionTemplate;


    /**
     * 其中有RuntimeException、Error、Throwable的异常以及子类，会触发事务回滚
     * @param producerId
     * @param customerId
     * @param price
     * @throws Exception
     */
    public void exchange(Long producerId, Long customerId, Long price) throws Exception {

        transactionTemplate.execute(status -> {
            customerService.buy(customerId, price);
            producerService.outBuy(producerId, price);
            return null;
        });
    }
}
